import React, { useEffect, useState, useRef } from "react";
import newsApi from "../../../service/api/news";
import { Card, Col, Row, List, Avatar, Space, Drawer } from "antd";
import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
  BarChartOutlined,
} from "@ant-design/icons";
import { ItemGroupBy, ObjectToArray } from "../../../utils";

// 按需引入Echars
import * as echarts from "echarts/core";
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from "echarts/components";
import { BarChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { PieChart } from "echarts/charts";
import { LabelLayout } from "echarts/features";

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer,
  PieChart,
  LabelLayout,
]);

const { Meta } = Card;

export default function Home() {
  const [viewList, setViewList] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const data = await newsApi.list({
        publishState: 2,
        _expand: "category",
        _sort: "view",
        _order: "desc",
        _limit: 10,
      });
      setViewList(data);
      console.log(data);
    };
    fetchData();
  }, []);

  const [starList, setStarList] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const data = await newsApi.list({
        publishState: 2,
        _expand: "category",
        _sort: "star",
        _order: "desc",
        _limit: 10,
      });
      setStarList(data);
      console.log(data);
    };
    fetchData();
  }, []);

  const {
    username,
    region,
    role: { roleName },
  } = JSON.parse(localStorage.getItem("user"));

  const [allList, setAllList] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      const data = await newsApi.list({
        publishState: 2,
        _expand: "category",
      });
      setAllList(data);
      const data1 = ObjectToArray(ItemGroupBy(data, "categoryId"));
      const barData = data1.map((item) => item.length);
      const barTitle = data1.map((item) => item[0].category.title);
      renderBarView(barTitle, barData);
    };
    fetchData();
    return () => {
      window.onresize = null;
    };
  }, []);

  // Echars
  const barRef = useRef();
  const paiRef = useRef();
  const [pieChat, setPieChat] = useState(null);
  const renderBarView = (barTitle, barData) => {
    echarts.use([GridComponent, BarChart, CanvasRenderer]);
    var myChart = echarts.init(barRef.current);
    var option;
    option = {
      title: {
        text: "新闻分类图示",
      },
      tooltip: {},
      legend: {
        data: ["数量"],
      },
      xAxis: {
        type: "category",
        data: barTitle,
        axisLabel: {
          rotate: "45",
        },
      },
      yAxis: {
        type: "value",
        minInterval: 1,
      },
      series: [
        {
          data: barData,
          type: "bar",
          name: "数量",
        },
      ],
    };

    option && myChart.setOption(option);

    window.onresize = () => {
      myChart.resize();
    };
  };
  const renderPieView = () => {
    const currentList = allList.filter((item) => item.author === username);
    const data1 = ObjectToArray(ItemGroupBy(currentList, "categoryId"));
    const pieData = data1.map((item) => {
      return {
        name: item[0].category.title,
        value: item.length,
      };
    });
    let myChart;
    if (!pieChat) {
      myChart = echarts.init(paiRef.current);
      setPieChat(myChart);
    } else {
      myChart = pieChat;
    }
    var option;

    option = {
      title: {
        text: "您的新闻分类数据",
        subtext: "仅统计已发布",
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "Access From",
          type: "pie",
          radius: "50%",
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };

    option && myChart.setOption(option);
  };

  // 抽屉组件
  const [visible, setVisible] = useState(false);

  return (
    <div className="site-card-wrapper">
      <Row gutter={16}>
        <Col span={8}>
          <Card
            title={
              <Space>
                <span>浏览排行</span>
                <BarChartOutlined />
              </Space>
            }
            bordered={false}
          >
            <List
              dataSource={viewList}
              renderItem={(item) => (
                <List.Item>
                  <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            title={
              <Space>
                <span>点赞排行</span>
                <BarChartOutlined />
              </Space>
            }
            bordered={false}
          >
            <List
              dataSource={starList}
              renderItem={(item) => (
                <List.Item>
                  <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
                </List.Item>
              )}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <SettingOutlined
                key="setting"
                onClick={() => {
                  setTimeout(() => {
                    setVisible(true);
                    renderPieView(allList);
                  }, 0);
                }}
              />,
              <EditOutlined key="edit" />,
              <EllipsisOutlined key="ellipsis" />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={username}
              description={
                <>
                  <b>{region || "全球"} - </b>
                  <span>{roleName}</span>{" "}
                </>
              }
            />
          </Card>
        </Col>
      </Row>
      <div
        ref={barRef}
        style={{
          marginTop: 20,
          width: "100%",
          height: 400,
        }}
      ></div>
      {/* 抽屉组件 */}
      <Drawer
        width="500px"
        title="个人新闻分类"
        placement="right"
        onClose={() => {
          setVisible(false);
        }}
        visible={visible}
      >
        <div
          ref={paiRef}
          style={{
            marginTop: 20,
            width: "100%",
            height: 400,
          }}
        ></div>
      </Drawer>
    </div>
  );
}
